package com.guokai2012.util;

import com.alibaba.fastjson.JSON;
import com.guokai2012.domain.LineData;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @Author: guokai
 * @Description: 数据持久化处理
 */
public class DataTipManager {
    private final String path;
    private FileUpDownQiNiuOss qiNiuOss;
    private boolean QNIsReady = false;
    private Consumer<Map<String, Object>> callFun;

    public DataTipManager(String tipPath, PropertiesManager propertiesManager) {
        this.path = tipPath;
        this.qiNiuOss = FileUpDownQiNiuOss.create(propertiesManager);
    }

    public void initTip(Consumer<Map<String, Object>> consumer) {
        this.callFun = consumer;
        File file = new File(path);
        //  如果下载文件失败，且本地 没有该文件，则使用本地 创建文件方式，创建文件
        Map<String, Object> map = new HashMap<>();
        if (null != qiNiuOss) {
            map = qiNiuOss.checkQiNiuExe(file.getName());
            if (200 == Integer.parseInt(map.get("code").toString())) {
                this.QNIsReady = true;
                qiNiuOss.getFile(file);
            }
        } else {
            map.put("code", 200);
            map.put("message", "");
        }
        callFun(map);
        if (!file.exists()) {
            outTipData(new ArrayList<>());
        }
    }

    private void callFun(Map<String, Object> map) {
        if (null != callFun) {
            callFun.accept(map);
        }
    }

    /**
     * 读文件
     */
    public List<LineData> getTipData() {
        List<LineData> lineData = new ArrayList<>();
        try (FileReader in = new FileReader(path)) {
            StringBuilder buffer = new StringBuilder();
            char[] chars = new char[1024];
            int readCount;
            while ((readCount = in.read(chars)) != -1) {
                buffer.append(chars, 0, readCount);
            }
            lineData = JSON.parseArray(buffer.toString(), LineData.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lineData;
    }

    /**
     * 写文件
     */
    public void outTipData(List<LineData> dataList) {
        try (FileWriter out = new FileWriter(path)) {
            out.write(JSON.toJSONString(dataList));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件价
     */
    public void upLoad() {
        if (QNIsReady) {
            Map<String, Object> map = qiNiuOss.upLoadFile(path);
            if (200 != Integer.parseInt(map.get("code").toString())) {
                callFun(map);
            }
        } else {
            System.out.println("七牛云未初始化成功，无需上传");
        }
    }
}
